package com.ruoyi.admin.web.controller.tool;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PdfTemplateFiller {

    public static void fillTemplateWithAutoDetection(
            String templatePath,
            String outputPath,
            Map<String, String> data,
            String fontPath) throws IOException {

        PDDocument document = null;
        try {
            // 1. 加载文档和字体
            document = PDDocument.load(new File(templatePath));
            PDType0Font font = PDType0Font.load(document, new File(fontPath));

            // 2. 查找占位符位置
            Map<String, TextPosition> placeholderPositions = findPlaceholderPositions(document);

            // 3. 替换占位符
            replacePlaceholders(document, placeholderPositions, data, font);

            // 4. 保存文档
            document.save(outputPath);
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }

    private static Map<String, TextPosition> findPlaceholderPositions(PDDocument document) throws IOException {
        final Map<String, TextPosition> positions = new HashMap<>();
        final StringBuilder currentText = new StringBuilder();
        final List<TextPosition> currentPositions = new ArrayList<>();

        PDFTextStripper stripper = new PDFTextStripper() {
            @Override
            protected void writeString(String text, List<TextPosition> textPositions) throws IOException {
                for (TextPosition position : textPositions) {
                    String character = position.getUnicode();

                    if (character.equals("$") || (currentText.length() > 0 && currentText.charAt(0) == '$')) {
                        currentText.append(character);
                        currentPositions.add(position);

                        if (character.equals("}") && currentText.toString().startsWith("${")) {
                            positions.put(currentText.toString(), currentPositions.get(0));
                            currentText.setLength(0);
                            currentPositions.clear();
                        }
                    } else {
                        currentText.setLength(0);
                        currentPositions.clear();
                    }
                }
            }
        };

        stripper.getText(document);
        return positions;
    }

    private static void replacePlaceholders(PDDocument document,
                                            Map<String, TextPosition> placeholderPositions,
                                            Map<String, String> data,
                                            PDType0Font font) throws IOException {

        for (Map.Entry<String, TextPosition> entry : placeholderPositions.entrySet()) {
            String placeholder = entry.getKey();
            TextPosition position = entry.getValue();
            String replacement = data.get(placeholder);

            if (replacement != null) {
                PDPage page = document.getPage(0);
                PDPageContentStream cs = new PDPageContentStream(
                        document, page,
                        PDPageContentStream.AppendMode.APPEND,
                        true, true);

                try {
// 调整后的覆盖和文本写入代码
                    float x = position.getX();
                    float y = position.getPageHeight() - position.getY(); // 转换为页面坐标系
                    float width = position.getWidth() * placeholder.length();
                    float height = position.getHeight();

//                    // 1. 用白色矩形覆盖原占位符
//                    cs.setNonStrokingColor(255, 255, 255);
//                    cs.addRect(position.getX(), position.getY() - position.getHeight(),
//                            position.getWidth() * placeholder.length(), position.getHeight());
//                    cs.fill();


                    // 1. 将原占位符文本颜色改为白色
                    PDColor whiteColor = new PDColor(new float[]{1.0f, 1.0f, 1.0f}, PDDeviceRGB.INSTANCE);
                    cs.setNonStrokingColor(whiteColor);

// 2. 写入新文本（调整Y坐标）
                    cs.setNonStrokingColor(0, 0, 0);
                    cs.setFont(font, position.getFontSize());
                    cs.beginText();
                    cs.newLineAtOffset(x, y - height/2); // 垂直居中
                    cs.showText(replacement);
                    cs.endText();
                } finally {
                    cs.close();
                }
            }
        }
    }

    public static void main(String[] args) {
        try {
            // 示例数据
            Map<String, String> data = new HashMap<>();
            data.put("${name}", "张三");
            data.put("${ege}", "31");
            data.put("${sex}", "男");
            data.put("${phone}", "13245678909");
            data.put("${email}", "93999999@qq.com");

            // 需要提供一个支持中文的TTF字体文件
            String fontPath = "D:\\XSource\\X-LifeButler\\x-admin\\src\\main\\resources\\simsun.ttf";

            // 填充模板
            fillTemplateWithAutoDetection("D:\\XSource\\X-LifeButler\\x-admin\\src\\main\\resources\\template.pdf", "D:\\XSource\\X-LifeButler\\x-admin\\src\\main\\resources\\output.pdf", data, fontPath);

            System.out.println("PDF模板填充成功！");
        } catch (IOException e) {
            System.err.println("PDF处理失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}